#include "CommonUtil.h"
#include "stdafx.h"
#include <stdio.h>
#include <WinCrypt.h>

unsigned long get_file_size(const char *path)
{
	unsigned long filesize = -1;
	FILE *fp;
	fopen_s(&fp, path, "r");
	if (fp == NULL)
		return filesize;
	fseek(fp, 0L, SEEK_END);
	filesize = ftell(fp);
	fclose(fp);
	return filesize;
}

char* GetImgToBase64(const char* pFilePath)
{
	USES_CONVERSION;
	if (PathFileExists(A2W(pFilePath)))
	{
		ULONG uSize = get_file_size(pFilePath);
		FILE* fp;
		fopen_s(&fp, pFilePath, "rb");
		char* inBuffer = new char[uSize];
		ULONG uReaded = fread(inBuffer, 1, uSize, fp);
		const BYTE* pbBinary = (const BYTE*)inBuffer;
		DWORD dwLen;
		CryptBinaryToStringA(pbBinary, uSize, CRYPT_STRING_BASE64, NULL, &dwLen);
		char* pCrypt1 = new char[dwLen];
		CryptBinaryToStringA(pbBinary, uSize, CRYPT_STRING_BASE64, pCrypt1, &dwLen);
		fclose(fp);
		delete[] inBuffer;
		return pCrypt1;
	}
	else
	{
		return "";
	}

}

void SetBase64ToImg(const char* pBase64, const char* pSaveImgPath)
{
	byte *pImg;
	if (NULL != pBase64)
	{
		DWORD   nNeed = 0;
		CryptStringToBinaryA(pBase64, 0, CRYPT_STRING_BASE64, NULL, &nNeed, NULL, NULL);
		if (nNeed)
		{
			pImg = new byte[nNeed];
			CryptStringToBinaryA(pBase64, 0, CRYPT_STRING_BASE64, pImg, &nNeed, NULL, NULL);
			FILE* fp2;
			fopen_s(&fp2, pSaveImgPath, "wb");
			ULONG uWrite = fwrite(pImg, 1, nNeed, fp2);
			fclose(fp2);
			delete[] pImg;
		}
	}
}